# -*- coding:utf-8 -*-
"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: ${DATE}:${TIME}
@product: ${PRODUCT_NAME}
=============================
"""

import sys
from PyQt5.QtWidgets import QDialog, QApplication

import gtyTools.RF_band
from uiFiles import ui_readerSet
import time
from gtyConfig import language
import uiTools
from gtyTools import RF_band, gtyTypes, gtyLog


class ReaderSetDialog(QDialog, ui_readerSet.Ui_readerSetDialog):

    def __init__(self, mainPage, eventQ, readerId=1, parent=None):
        super(ReaderSetDialog, self).__init__(parent)
        self.setupUi(self)
        uiTools.centerAndSetIcon(self)
        self.eventQ = eventQ
        self.mainPage = mainPage
        self.mode = ''
        self.readerId = readerId
        self.power = 31

        self.mainPage.eventEngine.eventList["ui_getReaderPower"].connect(self.getReaderPower)

        self.powerAddBtn.clicked.connect(self.powerAdd)
        self.powerMinBtn.clicked.connect(self.powerMin)
        self.setPowerBtn.clicked.connect(self.setPower)
        self.getPowerBtn.clicked.connect(self.getPower)
        self.setFreqBtn.clicked.connect(self.setBand)
        self.getFreqBtn.clicked.connect(self.getBand)
        self.setTypeBtn.clicked.connect(self.setType)
        self.getTypeBtn.clicked.connect(self.getType)

        self.mainPage.eventEngine.eventList["ui_getFreqBand"].connect(self.updateFreqBand)
        self.mainPage.eventEngine.eventList["ui_getReaderTypeAndVersion"].connect(self.updateReaderType)

        self.setWindowTitle("Reader" + str(readerId) + " Setting")
        # language
        # 处理不同的语言
        self.label.setText(language.readerSetting_reader)
        self.strSetReaderPower = ': Set reader power '
        self.strReadReaderPower = ': Read reader power '
        self.strSetBand = ': Set reader 1&2 band '
        self.strReadBand = ': Read reader 1&2 band '
        self.setPowerBtn.setText(language.readerSetting_setPower)
        self.getPowerBtn.setText(language.readerSetting_getPower)
        self.returnBtn.setText(language.readerSetting_back)
        self.label_1.setText(language.readerSetting_band)
        self.setFreqBtn.setText(language.readerSetting_setFreq)
        self.getFreqBtn.setText(language.readerSetting_getFreq)
        self.label_2.setText(language.readerSetting_type)
        self.setTypeBtn.setText(language.readerSetting_setType)
        self.getTypeBtn.setText(language.readerSetting_getType)
        self.readerTypes = [
            language.readerSetting_readerTypeA,
            language.readerSetting_readerTypeB1,
            language.readerSetting_readerTypeB2,
            language.readerSetting_readerTypeC,
            language.readerSetting_readerTypeD
        ]
        self.readerTypeVersionStm32 = [
            [1, 0],
            [2, 0],
            [2, 1],
            [3, 0],
            [4, 0]
        ]

        # 频率复选框
        self.rfBand = gtyTools.RF_band.RF_BAND()

        # 获取读写器功率
        self.getPower()
        time.sleep(0.1)
        self.getBand()
        self.setGeometry(-200, -200, self.width(), self.height())
        time.sleep(0.1)
        self.getType()

        # 获取配置文件
        self.configHandlers = gtyTypes.ConfigHandlers()

    # 发生事件
    def sendEvent(self, task, eventName, eventData=None):
        if eventData is None:
            eventData = []
        e = [eventName, eventData]
        try:
            if task.upper() in self.eventQ.keys():
                self.eventQ[task.upper()].put(e)
        except Exception as e:
            print(e)

    # 获取了读写器的功率
    def getReaderPower(self, d):
        readerId = int(d[0])
        print(__file__, d)
        self.label_power.setText(str(d[1]))
        if int(self.readerId) == readerId:
            self.label_power.setText(str(d[1]))
            self.power = int(d[1])

    # 功率加减
    def powerAdd(self):
        if self.power + 1 <= 33:
            self.power += 1
        self.label_power.setText(str(self.power))

    # 功率加减
    def powerMin(self):
        if self.power - 1 >= 5:
            self.power -= 1
        self.label_power.setText(str(self.power))

    # 设置读写功率
    def setPower(self):
        power = int(self.label_power.text())
        self.sendEvent('UART', 'uart_setReaderPower', [int(self.readerId) + 2, power])  # 设置读卡功率
        self.sendEvent('UI','ui_updateReaderPower',[self.readerId, power])
        self.label_info.setText(time.strftime('%H:%M:%S', time.localtime(time.time())) + self.strReadReaderPower)

    # 读取读写功率
    def getPower(self):
        self.sendEvent('UART', 'uart_getReaderPower', int(self.readerId) + 2)  # 读取读卡功率
        self.label_info.setText(time.strftime('%H:%M:%S', time.localtime(time.time())) + self.strSetReaderPower)

    # 获得读写器频段
    def getBand(self):
        self.sendEvent('UART', 'uart_freqBand', [0, int(self.readerId) + 2])
        self.label_info.setText(time.strftime('%H:%M:%S', time.localtime(time.time())) + self.strReadBand)

    #从字典的值获取键
    def get_key(self,dict,value):
        for k, v in dict.items():
            if v == value:
                return k

    # 设置读写器频段
    def setBand(self):
        #1月15日修改 新增从值获取键的函数，删掉了无法选择的频段导致键值与index对不上，qt的combobox.currentIndex返回的是第几个
        bandId = self.get_key(self.rfBand.bandDict,self.FreqComboBox.currentText())
        # 对于澳大利亚频段，保存在配置文件中
        if bandId == 9:
            print(__file__,"bandId write: ",bandId)
            self.configHandlers.machine.write("reader", "freqBand", "9")
            bandId = 0
        elif bandId == 0:
            print(__file__,"bandId write: ",bandId)
            self.configHandlers.machine.write("reader", "freqBand", "0")
            # 新增越南和南非
        elif bandId == 10:
            print(__file__, "bandId write: ", bandId)
            self.configHandlers.machine.write("reader", "freqBand", "10")
            bandId = 3
        elif bandId == 11:
            print(__file__, "bandId write: ", bandId)
            self.configHandlers.machine.write("reader", "freqBand", "11")
            bandId = 3
        elif bandId == 3:
            print(__file__, "bandId write: ", bandId)
            self.configHandlers.machine.write("reader", "freqBand", "3")
        self.sendEvent('UART', 'uart_freqBand', [1, bandId])
        print(__file__, 'set freq band:', bandId)
        self.sendEvent('UART', 'uart_freqBand', [1, bandId])
        print(__file__, 'set freq band:', bandId)
        self.label_info.setText(time.strftime('%H:%M:%S', time.localtime(time.time())) + self.strSetBand)


    def updateFreqBand(self, dataList):
        gtyLog.log.write(__file__, 'updateFreqBand:', dataList)
        if self.FreqComboBox.count() == 0:
            self.FreqComboBox.addItems(self.rfBand.getBandList())
        band = dataList[1]
        # 对于澳大利亚的频段
        configFileBandId = self.configHandlers.machine.read("reader", "freqBand", "int")
        gtyLog.log.write(__file__,band,configFileBandId)
        if band == 0 and configFileBandId == 9:
            band = 9
        # 新增其他频段
        if band == 3 and configFileBandId == 10:
            band = 10
        if band == 3 and configFileBandId == 11:
            band = 11
        self.FreqComboBox.setCurrentText(self.rfBand.bandDict[band])

    # 设置读卡器类型
    def setType(self):
        comboIndex = self.typeComboBox.currentIndex()
        readerType = self.readerTypeVersionStm32[comboIndex][0]
        version = self.readerTypeVersionStm32[comboIndex][1]
        self.sendEvent('UART', 'uart_readerTypeAndVersion', [1, int(self.readerId) + 2, readerType, version])

    # 获得读卡器类型
    def getType(self):
        self.sendEvent('UART', 'uart_readerTypeAndVersion', [0, int(self.readerId) + 2, 0, 0])

    # 刷新读卡器类型
    def updateReaderType(self, dataList):
        gtyLog.log.write(__file__, "update reader type", dataList)
        if self.typeComboBox.count() == 0:
            self.typeComboBox.addItems(self.readerTypes)
        try:
            readerType = dataList[0 + (self.readerId - 1) * 2]
            readerVersion = dataList[1 + (self.readerId - 1) * 2]
            readerIndex = 99
            for i in range(0, len(self.readerTypeVersionStm32)):
                if self.readerTypeVersionStm32[i][0] == readerType and self.readerTypeVersionStm32[i][1] == readerVersion:
                    readerIndex = i
                    break
            if readerIndex == 99:
                self.typeComboBox.setCurrentText('')
            else:
                self.typeComboBox.setCurrentText(self.readerTypes[readerIndex])
        except Exception as e:
            gtyLog.log.write(__file__, "update reader type error", e)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = ReaderSetDialog(None, None, None, None)
    form.show()
    sys.exit(app.exec_())
